//
//  mm_preViewRecordViewController.m
//  HondaPro_2
//
//  Created by Eric on 13-7-5.
//  Copyright (c) 2013年 glendale. All rights reserved.
//

#import "mm_preViewRecordViewController.h"

@interface mm_preViewRecordViewController ()

@end

@implementation mm_preViewRecordViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
    
    self.nPicNums = [modelIns.arrRecodeList count];
    
    self.recordViewCon = [[recordViewController alloc] init];
    [self.recordViewCon prepareForRecord];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - button 的回调方法

- (IBAction)backBtnPressed:(UIButton *)sender
{
    NSLog(@"backBtnPressed !!!");
    
    //跳回上一级页面
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)homeBtnPressed:(UIButton *)sender
{
    NSLog(@"homeBtnPressed !!!");
    
    //跳回主界面
    [self.navigationController popToRootViewControllerAnimated:YES];
}

#pragma mark - 方法重写

//此处添加View
- (mm_SLCoverView *)coverFlowView:(mm_SLCoverFlowView *)coverFlowView coverViewAtIndex:(NSInteger)index
{
    mm_SLCoverView *view = [[mm_SLCoverView alloc] initWithFrame:CGRectMake(0.0, 0.0, 100.0, 100.0)];
    
    view.backgroundColor = [UIColor whiteColor];
    
    /*给View上添加六宫格*/
    NSDictionary *dicForRect = [NSDictionary dictionaryWithObjectsAndKeys:
                                [NSValue valueWithCGRect:CGRectMake(0+2, 0+50, 220, 165)],@"page1",
                                [NSValue valueWithCGRect:CGRectMake(250+2, 0+50, 220, 165)],@"page2",
                                [NSValue valueWithCGRect:CGRectMake(500+2, 0+50, 220, 165)],@"page3",
                                [NSValue valueWithCGRect:CGRectMake(0+2, 195+50, 220, 165)],@"page4",
                                [NSValue valueWithCGRect:CGRectMake(250+2, 195+50, 220, 165)],@"page5",
                                [NSValue valueWithCGRect:CGRectMake(500+2, 195+50, 220, 165)],@"page6", nil];
    
    //贴预览图的个数为：nPicDis
    int nPicDis = (self.nPicNums-6*index) >= 6 ? (6) : (self.nPicNums-6*index);
    for (int i = 0; i<nPicDis; i++)
    {
        NSString *strKey = [NSString stringWithFormat:@"page%i",i+1];
        CGRect rect = (CGRect)[[dicForRect objectForKey:strKey]CGRectValue];
        UIView *baView = [[UIView alloc] initWithFrame:rect];
        [baView setBackgroundColor:[[UIColor alloc]initWithRed:226.00/255 green:226.00/255 blue:226.00/255 alpha:1]];
        UIImageView *imgView = [_arrAllRecordFaceImgView objectAtIndex:(6*index)+i];
    //imgView.backgroundColor = [UIColor whiteColor];
        [imgView setImage:[UIImage imageNamed:MM_RECORD_PAUSE_PNG_]];
        imgView.frame = CGRectMake(60, 32, 100, 100);
        imgView.tag = index*6 + i + 1;//标记tag值的目的就是可以通过此值找到要播放的录音
        [baView addSubview:imgView];
        [view addSubview:baView];
        
//        //给 imgView 上添加一个label，显示信息为录音的序列
//        CGRect rectLbl = CGRectMake(imgView.frame.size.width-100, imgView.frame.size.height-100, 100, 100);
//        UILabel *lbl = [[UILabel alloc] initWithFrame:rectLbl];
//        lbl.text = [NSString stringWithFormat:@"录音：%i",imgView.tag];
//        lbl.backgroundColor = [UIColor clearColor];
//        [imgView addSubview:lbl];
        
        //给所有的 imageView 添加手势
        UIGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(SelectTap:)];
        recognizer.delegate =self;
        [imgView setUserInteractionEnabled:YES];//这句很重要特别是imgView
        [imgView addGestureRecognizer:recognizer];
    }
    /*end of 给View上添加六宫格*/
    
    return view;
}

-(void)SelectTap:(UITapGestureRecognizer*)recognizer
{
    NSLog(@"selected !!!");
    
    /*
     此处的逻辑：
     （1）如果是查看模式，就调用查看模式的代码，return；
     （2）如果是编辑模式，就设置要删除的图片的下标，并且重新设置按钮的状态
     */
    
    UIView *view = recognizer.view;
    UIImageView *imgView = (UIImageView *)view;
    
    //（1）如果是查看模式，就调用查看模式的代码，return；
    if (MM_PIC_SCAN_MODE_ == _picMode)
    {
        [self.recordViewCon playback:[self imgViewsIndexInPicModelByImgView:imgView]];
        
        _currImgViewSelToPlay = imgView;
        [_currImgViewSelToPlay setImage:[UIImage imageNamed:MM_RECORD_PLAY_PNG_]];
        
        [HelpClass setUpTheStateButtonEnableState:MM_PIC_BTN_ENABLED_ withBtn:self.stopBtn];

        return;
    }
    
    //（2）如果是编辑模式，就设置要删除的图片的下标，并且重新设置按钮的状态
    if (MM_PIC_EDIT_MODE_ == _picMode)
    {
        _picIndexToDel = [self imgViewsIndexInPicModelByImgView:imgView];
        
        int i = 0;
        if ((i = [self picIndexInDelArrayByReference:_picIndexToDel]) != -1)
        {
            //选中的索引已经被选择过，将该索引移除掉
            [_arrAllPicIndexToDel removeObjectAtIndex:i];
        }
        else
        {
            //将要删除的索引存入数组中
            [_arrAllPicIndexToDel addObject:[NSNumber numberWithInteger:_picIndexToDel]];
        }
        
        [HelpClass setUpTheStateButtonEnableState:MM_PIC_BTN_DISABLED_ withBtn:self.editBtnIns];
        [HelpClass setUpTheStateButtonEnableState:MM_PIC_BTN_ENABLED_ withBtn:self.deleteBtnIns];
        [HelpClass setUpTheStateButtonEnableState:MM_PIC_BTN_ENABLED_ withBtn:self.cancelBtnIns];
        
        if ([_arrAllPicIndexToDel count] == 0)
        {
            [HelpClass setUpTheStateButtonEnableState:MM_PIC_BTN_DISABLED_ withBtn:self.deleteBtnIns];
        }
        
        //重新标注选中的图标
        [self remarkAllThePicSmallIcon];
    }
}

#pragma mark - 创建标题－重写父类方法

-(void)createTitle
{
    UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(150, 20, 120, 50)];
    lbl.textColor = [HelpClass colorWithHexString:@"666666"];
    lbl.font = [UIFont systemFontOfSize:30];
    lbl.text = @"录音查看";
    [self.view addSubview:lbl];
}

- (IBAction)editBtnPressed:(UIButton *)sender
{
    /*
     （1）设置编辑按钮的状态为禁能状态、删除按钮的状态为禁能状态、取消按钮状态为使能状态；
     （2）设置图片的预览模式为编辑模式
     */
    
    //（1）设置编辑按钮的状态为禁能状态、删除按钮的状态为禁能状态、取消按钮状态为使能状态；
    [HelpClass setUpTheStateButtonEnableState:MM_PIC_BTN_DISABLED_ withBtn:self.editBtnIns];
    [HelpClass setUpTheStateButtonEnableState:MM_PIC_BTN_DISABLED_ withBtn:self.deleteBtnIns];
    [HelpClass setUpTheStateButtonEnableState:MM_PIC_BTN_ENABLED_ withBtn:self.cancelBtnIns];
    
    //（2）设置图片的预览模式为编辑模式
    _picMode = MM_PIC_EDIT_MODE_;
}

- (IBAction)deleteBtnPressed:(UIButton *)sender
{
    /*
     （1）调用删除图片的接口,DeleteOutCheckPic.aspx?picName=20130901132859&operatorID=2001
     */
    
    MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
    
    _nCountPicToDel = [_arrAllPicIndexToDel count];
    
    if (_nCountPicToDel == 0)
    {
        UIAlertView *alerVeiw = [[UIAlertView alloc] initWithTitle:@"提示信息" message:@"请选择要删除的录音！！！" delegate:self cancelButtonTitle:@"我知道了" otherButtonTitles:nil, nil];
        [alerVeiw show];
        
        return;
    }
    
    [SVProgressHUD showWithStatus:@"正在删除" maskType:SVProgressHUDMaskTypeGradient];
    
    _picIndexToDel = [[_arrAllPicIndexToDel objectAtIndex:[_arrAllPicIndexToDel count]-_nCountPicToDel] integerValue];
    
    //图片名称
    modelIns.strCurrentPicName = [self picNameByIndex:_picIndexToDel];
    
    //接口请求
    NSMutableArray *arrTmp = [NSMutableArray array];
    [arrTmp addObject:@"recordName"];
    [arrTmp addObject:[self picPureNameByOriginalName:[[modelIns.arrRecodeList objectAtIndex:_picIndexToDel] objectForKey:MM_RECORD_LIST_RECORD_NAME_KEY_STR_]]];
    
    [arrTmp addObject:@"operatorID"];
    [arrTmp addObject:modelIns.strCurrentSalerId];
    
    [HelpClass getWebServiceDataByString:MM_DELETE_FUNCTION_CHECK_RECORDING_ andArrObject:arrTmp];
    
    _nCountPicToDel--;
}

- (IBAction)cancelBtnPressed:(UIButton *)sender
{
    /*
     （1）更新图片预览界面；
     */
    
    //（1）更新图片预览界面
    [self updateAllThePicScan];
}

//注册消息
-(void)addAllObserver
{
    //注册图片删除的消息
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getDeleteServerMsg:) name:MM_DELETE_FUNCTION_CHECK_RECORDING_ object:nil];
    
    //注册暂停录音的的消息
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pauseTheRecordInTime) name:MM_RECORD_PAUSE_MSG_ object:nil];
}

//移除消息
-(void)removeAllObserver
{
    //移除本类中的消息
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

//设置整个界面数据
-(void)setUpAllThePicScanData
{
//    self.nPicNums = [[mm_picRecodeDataModel sharedModelIns].arrForAllCapturePic count];
//    
//    [_coverFlowView removeFromSuperview];
//    [self setUpInit];
//    
//    [_coverFlowView reloadData];
//    
//    //当前的模式－－－查看、编辑
//    _picMode = MM_PIC_SCAN_MODE_;
//    //当前要删除的下标
//    _picIndexToDel = NSNotFound;
    
    self.nPicNums = [[MainMenuDataModel sharedMainMenuDataModel].arrRecodeList count];
    [self initAllTheImgViewToDis];
    
    [_coverFlowView removeFromSuperview];
    [self setUpInit];
    
    [_coverFlowView reloadData];
    
    //当前的模式－－－查看、编辑
    _picMode = MM_PIC_SCAN_MODE_;
    //当前要删除的下标
    _picIndexToDel = NSNotFound;
    
    _arrAllPicIndexToDel = [NSMutableArray array];
}

//更新图片预览界面
-(void)updateAllThePicScan;
{
    /*
     （1）如果图片界面权限为查看，设置编辑按钮的状态为禁能状态、删除按钮的状态为禁能状态、取消按钮状态为禁能状态；
     （2）如果图片界面模式为编辑，设置编辑按钮的状态为使能状态、删除按钮的状态为禁能状态、取消按钮状态为禁能状态；
     （3）重新设置界面的数据
     */
    
    //（1）如果图片界面权限为查看，设置编辑按钮的状态为禁能状态、删除按钮的状态为禁能状态、取消按钮状态为禁能状态；
    //（2）如果图片界面权限为编辑，设置编辑按钮的状态为使能状态、删除按钮的状态为禁能状态、取消按钮状态为禁能状态；
    if (MM_PIC_CAN_NOT_UPDATE_ == self.nLimitOfAuthority)
    {
        [HelpClass setUpTheStateButtonEnableState:MM_PIC_BTN_DISABLED_ withBtn:self.editBtnIns];
        [HelpClass setUpTheStateButtonEnableState:MM_PIC_BTN_DISABLED_ withBtn:self.deleteBtnIns];
        [HelpClass setUpTheStateButtonEnableState:MM_PIC_BTN_DISABLED_ withBtn:self.cancelBtnIns];
    }
    else if (MM_PIC_CAN_UPDATE_ == self.nLimitOfAuthority)
    {
        [HelpClass setUpTheStateButtonEnableState:MM_PIC_BTN_ENABLED_ withBtn:self.editBtnIns];
        [HelpClass setUpTheStateButtonEnableState:MM_PIC_BTN_DISABLED_ withBtn:self.deleteBtnIns];
        [HelpClass setUpTheStateButtonEnableState:MM_PIC_BTN_DISABLED_ withBtn:self.cancelBtnIns];
    }
    
    //（3）重新设置界面的数据
    [self setUpAllThePicScanData];
}

//通过本类中的UIimageView,找到其在界面中的编号
-(NSInteger)imgViewsIndexInPicModelByImgView:(UIImageView *)imgView
{
    return [_arrAllRecordFaceImgView indexOfObject:imgView];
}

//根据编号，由数据模型中取得图片名称,xxxx.jpg
-(NSString *)picNameByIndex:(NSInteger)index
{
    MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
    
    if ([modelIns.arrRecodeList count] > index)
    {
        return [[modelIns.arrRecodeList objectAtIndex:index] objectForKey:MM_RECORD_LIST_RECORD_NAME_KEY_STR_];
    }
    
    return nil;
}

//获取图片名xxxx，参数为xxxx.jpg
-(NSString *)picPureNameByOriginalName:(NSString *)picName
{
    NSRange range = [picName rangeOfString:@"."];
    
    return [picName substringToIndex:range.location];
}

//调用图片删除接口的回调方法
-(void)getDeleteServerMsg:(NSNotification *)notification
{
    NSDictionary *theJson = [NSJSONSerialization JSONObjectWithData:(NSData*)notification.object options:NSJSONReadingMutableLeaves error:Nil];
    NSLog(@"%@",theJson);
    
    /*
     {"error_code":-1,"error_msg":"DMS提示信息：不存在该图片！！"}
     */
    
    /*
     （1）如果删除成功，提示删除成功；否则提示删除失败，return；
     （2）更新作业单里边图片列表；
     （3）更新图片预览界面
     */
    
    if (_nCountPicToDel <= 0)
    {
        
        [SVProgressHUD dismiss];
        
        UIAlertView *alerVeiw = [[UIAlertView alloc] initWithTitle:@"提示信息" message:@"删除成功！！！" delegate:self cancelButtonTitle:@"我知道了" otherButtonTitles:nil, nil];
        [alerVeiw show];
        
        for (int i = 0; i<[_arrAllPicIndexToDel count]; i++)
        {
            _picIndexToDel = [[_arrAllPicIndexToDel objectAtIndex:i] integerValue];
            //（2）更新作业单里边图片列表；
            MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
            modelIns.arrRecodeList = [NSMutableArray arrayWithArray:modelIns.arrRecodeList];
            [modelIns.arrRecodeList removeObjectAtIndex:_picIndexToDel];
            
            _arrAllRecordFaceImgView = [NSMutableArray arrayWithArray:_arrAllRecordFaceImgView];
            [_arrAllRecordFaceImgView removeObjectAtIndex:_picIndexToDel];
        }
        
        //（3）更新图片预览界面
        [self updateAllThePicScan];
    }
    else
    {
        MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
        
        _picIndexToDel = [[_arrAllPicIndexToDel objectAtIndex:[_arrAllPicIndexToDel count]-_nCountPicToDel] integerValue];
        
        //图片名称
        modelIns.strCurrentPicName = [self picNameByIndex:_picIndexToDel];
        
        //接口请求
        NSMutableArray *arrTmp = [NSMutableArray array];
        [arrTmp addObject:@"recordName"];
        [arrTmp addObject:[self picPureNameByOriginalName:[[modelIns.arrRecodeList objectAtIndex:_picIndexToDel] objectForKey:MM_RECORD_LIST_RECORD_NAME_KEY_STR_]]];
        
        [arrTmp addObject:@"operatorID"];
        [arrTmp addObject:modelIns.strCurrentSalerId];
        
        [HelpClass getWebServiceDataByString:MM_DELETE_FUNCTION_CHECK_RECORDING_ andArrObject:arrTmp];
        
        _nCountPicToDel--;
    }
}

//初始化所有要显示的视图
-(void)initAllTheImgViewToDis
{
    MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
    
    _arrAllRecordFaceImgView = [NSMutableArray array];
    
    for (int i = 0; i<[modelIns.arrRecodeList count]; i++)
    {
        [_arrAllRecordFaceImgView addObject:[[UIImageView alloc] init]];
    }
}

//暂停录音
-(void)pauseTheRecordInTime
{
    [_currImgViewSelToPlay setImage:[UIImage imageNamed:MM_RECORD_PAUSE_PNG_]];
    
    //（3）设置停止播放按钮禁能
    [HelpClass setUpTheStateButtonEnableState:MM_PIC_BTN_DISABLED_ withBtn:self.stopBtn];
}

- (void)viewDidUnload {
    [self setStopBtn:nil];
    [super viewDidUnload];
}

- (IBAction)stopBtnPressed:(UIButton *)sender
{
    /*
     （1）调用停止播放的方法
     （2）发送停止播放的消息
     （3）设置停止播放按钮禁能
     */
    
    //（1）调用停止播放的方法
    [self.recordViewCon stopBack];
    
    //（2）发送停止播放的消息
    [self pauseTheRecordInTime];
    
    //（3）设置停止播放按钮禁能
    [HelpClass setUpTheStateButtonEnableState:MM_PIC_BTN_DISABLED_ withBtn:self.stopBtn];
}

//删除的项目是否在选中列表中，是的话返回数组的编号,否则返回-1
-(NSInteger)picIndexInDelArrayByReference:(NSInteger)_indexXingCan
{
    for (int i = 0; i<[_arrAllPicIndexToDel count]; i++)
    {
        NSInteger indexTmp = [[_arrAllPicIndexToDel objectAtIndex:i] integerValue];
        if (_indexXingCan == indexTmp)
        {
            return i;
        }
    }
    
    return -1;
}

//重新标注要删除的图片图标
-(void)remarkAllThePicSmallIcon
{
    //去掉所有的图标
    for (id obj in _arrAllRecordFaceImgView)
    {
        for (int i = 0; i<[[obj subviews] count]; i++)
        {
            [[[obj subviews] objectAtIndex:i] removeFromSuperview];
        }
    }
    
    for (int i = 0; i<[_arrAllPicIndexToDel count]; i++)
    {
        NSInteger indexTmp = [[_arrAllPicIndexToDel objectAtIndex:i] integerValue];
        UIImageView *imgView = [_arrAllRecordFaceImgView objectAtIndex:indexTmp];
        //（2）给选中的imgView的右下角添加一个小的对号图标
        UIImageView *imgViewTmp = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"对号.png"]];
        imgViewTmp.backgroundColor = [UIColor clearColor];
        imgViewTmp.frame = CGRectMake(imgView.frame.size.width-40, imgView.frame.size.height-40, 40, 40);
        [imgView addSubview:imgViewTmp];
    }
}

@end
